var gulp = require('gulp')
var browserSync = require('browser-sync')
var postcss = require('gulp-postcss')
var gulp_less = require('gulp-less')
var aspectratio = require('postcss-aspect-ratio-mini')
var writesvg = require('postcss-write-svg')
var px2rem = require('postcss-px2rem')
var gulp_minify_css = require('gulp-minify-css')
var Autoprefixer = require('gulp-autoprefixer')
var autoprefixer = require('autoprefixer-core')
var reload = browserSync.reload

gulp.task('serve', ['less'], () => {
  browserSync.init({ // 启动Browsersync服务
    server: {
      baseDir: './app', // 启动服务的目录 默认 index.html
      index: 'index.html' // 自定义启动文件名
    },
    open: 'local', // external/local
    injectChanges: true // 注入CSS改变
  })

  // 监听文件变化，执行相应任务
  gulp.watch('./app/less/**/*.less', ['less'])
  gulp.watch('./app/*.html').on('change', reload)
})

gulp.task('less', function () {
  var processors = [
    px2rem({
      remUnit: 75
    }),
    aspectratio,
    writesvg({
      utf8: true,
    }),
    autoprefixer({
      browsers: ['Android 4.1', 'iOS 7.1', 'Chrome > 31', 'ff > 31', 'ie >= 10']
    })
  ]
  return gulp.src('./app/less/**/*.less')
    .pipe(gulp_less())
    .pipe(postcss(processors))
    .pipe(Autoprefixer({
      browsers: ['last 2 versions'], //主流浏览器的最新两个版本
      cascade: true, //是否美化属性值 默认：true
      remove: true //是否去掉不必要的前缀 默认：true
    }))
    .pipe(gulp_minify_css())
    .pipe(gulp.dest('./app/css'))
    .pipe(reload({
      stream: true
    }))
})